<template>
  <div class="region-management-container">
    <!-- 卡片式容器 -->
    <el-card class="main-card">
      <!-- 标题栏 -->
      <div slot="header" class="card-header">
        <span class="title">区域管理</span>
      </div>

      <!-- 搜索筛选区域 -->
      <div class="search-container">
        <el-form ref="form" :model="queryParams" label-width="90px" inline>
          <el-form-item label="区域名称">
            <el-input v-model="queryParams.name" size="small" placeholder="请输入区域名称" style="width: 180px;"></el-input>
          </el-form-item>
          <el-form-item label="区域代码">
            <el-input v-model="queryParams.regionCode" size="small" placeholder="请输入区域代码" style="width: 180px;"></el-input>
          </el-form-item>
          <el-form-item label="区域层级">
            <el-select v-model="queryParams.level" size="small" placeholder="请选择层级" style="width: 150px;">
              <el-option label="省份" :value="1"></el-option>
              <el-option label="城市" :value="2"></el-option>
              <el-option label="区县" :value="3"></el-option>
              <el-option label="乡镇/街道" :value="4"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="区域状态">
            <el-select v-model="queryParams.status" size="small" placeholder="请选择状态" style="width: 120px;">
              <el-option label="正常" :value="1"></el-option>
              <el-option label="禁用" :value="0"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="small" @click="refreshTree">搜索</el-button>
            <el-button icon="el-icon-refresh" size="small" @click="resetQuery" style="margin-left: 10px;">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 操作按钮组 -->
      <div class="button-group">
        <el-button type="primary" icon="el-icon-plus" size="small" @click="handleAddRoot">新增根节点</el-button>
      </div>

      <!-- 异步树形结构展示 - 添加ref属性 -->
      <div class="tree-container">
        <el-tree
          ref="regionTree"
        :data="treeData"
        :props="treeProps"
        :load="loadNode"
        lazy
        show-checkbox
        node-key="id"
        :default-expand-all="true"
        @node-click="handleNodeClick"
        @node-contextmenu="handleRightClick"
        class="region-tree"
        >
        <template #default="{ node, data }">
            <span class="tree-node-content">
              <span class="node-info">
                <span :style="{ fontWeight: node.level === 1 ? 'bold' : 'normal' }">
                  {{ data.name }}
                </span>
                <span class="node-code" v-if="data.regionCode">
                  [{{ data.regionCode }}]
                </span>
              </span>
              <span class="node-location">
                <span class="location-item">
                  经度：{{ data.longitude || '-' }}
                </span>
                <span class="location-item">
                  纬度：{{ data.latitude || '-' }}
                </span>
              </span>
              <span class="node-meta">
                <span class="node-level">
                  {{ getLevelText(data.level) }}
                </span>
                <span class="node-status" :class="data.status === 1 ? 'status-normal' : 'status-disabled'">
                  {{ data.status === 1 ? '正常' : '禁用' }}
                </span>
                <span class="node-actions">
                  <el-button
                    type="text"
                    size="mini"
                    @click.stop="handleAddChild(data)"
                    v-if="data.level < 4"
                    class="action-btn"
                  >
                    <i class="el-icon-plus"></i>
                  </el-button>
                  <el-button
                    type="text"
                    size="mini"
                    @click.stop="handleEdit(data)"
                    class="action-btn"
                  >
                    <i class="el-icon-edit"></i>
                  </el-button>
                  <el-button
                    type="text"
                    size="mini"
                    @click.stop="handleDelete(data)"
                    class="action-btn delete-btn"
                  >
                    <i class="el-icon-delete"></i>
                  </el-button>
                </span>
              </span>
            </span>
        </template>
        </el-tree>
      </div>
    </el-card>

    <!-- 新增/编辑弹窗 -->
    <el-dialog title="区域信息" :visible.sync="dialogVisible" width="500px">
      <el-form ref="regionForm" :model="regionForm" :rules="rules" label-width="120px">
        <el-form-item label="上级区域" v-if="regionForm.parentId !== 0">
          <el-input v-model="parentRegionName" disabled placeholder="无"></el-input>
        </el-form-item>
        <el-form-item label="区域划分" v-if="regionForm.parentId !== 0">
          <el-input v-model="regionDivision" disabled placeholder="无"></el-input>
        </el-form-item>
        <el-form-item label="区域名称" prop="name">
          <el-input v-model="regionForm.name" placeholder="请输入区域名称"></el-input>
        </el-form-item>
        <el-form-item label="区域简称" prop="shortName">
          <el-input v-model="regionForm.shortName" placeholder="请输入区域简称"></el-input>
        </el-form-item>
        <el-form-item label="区域代码" prop="regionCode">
          <el-input v-model="regionForm.regionCode" placeholder="请输入区域代码"></el-input>
        </el-form-item>
        <el-form-item label="经度">
          <el-input v-model="regionForm.longitude" placeholder="请输入经度"></el-input>
        </el-form-item>
        <el-form-item label="纬度">
          <el-input v-model="regionForm.latitude" placeholder="请输入纬度"></el-input>
        </el-form-item>
        <el-form-item label="排序号">
          <el-input-number v-model="regionForm.sort" :min="0"></el-input-number>
        </el-form-item>
        <el-form-item label="区域状态">
          <el-select v-model="regionForm.status" placeholder="请选择区域状态">
            <el-option label="正常" :value="1"></el-option>
            <el-option label="禁用" :value="0"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 删除确认弹窗 -->
    <el-dialog title="删除确认" :visible.sync="deleteDialogVisible" width="400px">
      <div style="padding: 20px 0; line-height: 1.6;">
        <p>删除操作会递归删除所有子节点，包括：</p>
        <p style="color: #F56C6C; margin-top: 10px;">
          {{ deleteRegionName }} 下的所有
          <span v-if="deleteRegionLevel === 1">城市、区县和乡镇</span>
          <span v-if="deleteRegionLevel === 2">区县和乡镇</span>
          <span v-if="deleteRegionLevel === 3">乡镇</span>
        </p>
        <p style="margin-top: 10px;">此操作不可恢复，确定要删除吗？</p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="deleteDialogVisible = false">取 消</el-button>
        <el-button type="danger" @click="confirmDelete">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getChildRegions, getRegionById, addRegion, updateRegion, deleteRegion } from "@/api/njt/basic/region";

export default {
  name: 'RegionalManagement',
  data() {
    return {
      /** 查询条件 */
      queryParams: {
        name: "",
        regionCode: "",
        level: undefined,
        status: undefined
      },
      /** 树形结构数据 */
      treeData: [],
      /** 树形结构配置 */
      treeProps: {
        label: 'name',
        children: 'children',
        isLeaf: node => {
          if (!node.data) return true;
          return node.data.hasChildren !== undefined ? !node.data.hasChildren : false;
        }
      },
      /** 当前激活的筛选参数，用于所有层级节点的查询 */
      activeFilterParams: {},
      /** 弹窗相关 */
      dialogVisible: false,
      deleteDialogVisible: false,
      /** 表单数据 */
      regionForm: {
        id: null,
        parentId: 0,
        name: '',
        shortName: '',
        regionCode: '',
        level: 1,
        longitude: '',
        latitude: '',
        sort: 0,
        status: 1
      },
      /** 父区域名称 */
      parentRegionName: '',
      /** 区域划分路径 */
      regionDivision: '',
      /** 删除相关 */
      deleteRegionId: '',
      deleteRegionName: '',
      deleteRegionLevel: 1,
      /** 表单验证规则 */
      rules: {
        name: [
          { required: true, message: '请输入区域名称', trigger: 'blur' },
          { max: 50, message: '区域名称长度不能超过50个字符', trigger: 'blur' }
        ],
        regionCode: [
          { required: true, message: '请输入区域代码', trigger: 'blur' },
          { max: 20, message: '区域代码长度不能超过20个字符', trigger: 'blur' }
        ]
      }
    };
  },

  methods: {
    /** 加载节点数据 - 核心修复：确保所有层级节点都使用相同的筛选参数 */
    loadNode(node, resolve) {
      // 使用当前激活的筛选参数，确保根节点和子节点使用相同的筛选条件
      const filterParams = { ...this.activeFilterParams };

      // 打印调试信息，确认参数是否正确传递
      console.log(`加载节点[层级:${node.level}, ID:${node.data?.id || 'root'}]`, filterParams);

      if (node.level === 0) {
        this.$modal.loading("正在加载数据，请稍候...");
        getChildRegions(0, filterParams).then(response => {
          this.$modal.closeLoading();
          const data = Array.isArray(response.data) ? response.data : [];
          const formattedData = data.map(item => ({
            ...item,
            hasChildren: item.hasChildren !== undefined ? item.hasChildren : false,
            // 计算是否有子节点（即使为空也保留展开按钮，以便筛选后能显示结果）
            // hasChildren: item.hasChildren || true
          }));
          resolve(formattedData);
        }).catch(error => {
          this.$modal.closeLoading();
          this.$message.error("数据加载失败：" + (error.message || "网络异常"));
          resolve([]);
        });
      } else {
        getChildRegions(node.data.id, filterParams).then(response => {
          const data = Array.isArray(response.data) ? response.data : [];
          const formattedData = data.map(item => ({
            ...item,
            hasChildren: item.hasChildren !== undefined ? item.hasChildren : false,
            // 计算是否有子节点
            // hasChildren: item.hasChildren || true
          }));
          resolve(formattedData);
        }).catch(error => {
          this.$message.error("子节点加载失败：" + (error.message || "网络异常"));
          resolve([]);
        });
      }
    },

    handleNodeClick(data) {
      console.log('节点点击:', data);
    },

    handleRightClick(node, event) {
      event.preventDefault();
      console.log('右键点击:', node.data);
    },

    /** 刷新树 - 修复引用错误 */
    refreshTree() {
      this.activeFilterParams = {
        name: this.queryParams.name,
        regionCode: this.queryParams.regionCode,
        level: this.queryParams.level,
        status: this.queryParams.status
      };

      this.treeData = [];

      // 正确使用组件引用并检查方法是否存在
      this.$nextTick(() => {
        // 确保组件已加载且存在getNode方法
        if (this.$refs.regionTree && typeof this.$refs.regionTree.getNode === 'function') {
          const rootNode = this.$refs.regionTree.getNode(0);
          if (rootNode) {
            rootNode.loadData();
          }
        } else {
          // 兼容处理：如果无法获取节点，直接重新加载根节点
          this.loadNode({ level: 0 }, (data) => {
            this.treeData = data;
          });
        }
      });
    },

    resetQuery() {
      this.queryParams = {
        name: "",
        regionCode: "",
        level: undefined,
        status: undefined
      };
      this.refreshTree();
    },

    handleAddRoot() {
      this.dialogVisible = true;
      this.regionForm = {
        id: null,
        parentId: 0,
        name: '',
        shortName: '',
        regionCode: '',
        level: 1,
        longitude: '',
        latitude: '',
        sort: 0,
        status: 1
      };
      this.parentRegionName = '';
      this.regionDivision = '';
    },

    handleAddChild(data) {
      this.dialogVisible = true;
      this.regionForm = {
        id: null,
        parentId: data.id,
        name: '',
        shortName: '',
        regionCode: '',
        level: data.level + 1,
        longitude: '',
        latitude: '',
        sort: 0,
        status: 1
      };

      this.parentRegionName = data.name;
      this.buildRegionDivision(data);
    },

    buildRegionDivision(row) {
      const getFullPath = (region, path = []) => {
        path.unshift(region.name);
        if (region.parentId !== 0) {
          return getRegionById(region.parentId).then(parent => {
            return getFullPath(parent.data, path);
          });
        }
        return Promise.resolve(path);
      };

      getFullPath(row).then(path => {
        this.regionDivision = path.join(' > ');
      });
    },

    handleEdit(data) {
      this.dialogVisible = true;
      getRegionById(data.id).then(response => {
        this.regionForm = response.data;
        if (this.regionForm.parentId !== 0) {
          getRegionById(this.regionForm.parentId).then(parentRes => {
            this.parentRegionName = parentRes.data.name;
            this.buildRegionDivision(response.data);
          });
        } else {
          this.parentRegionName = '';
          this.regionDivision = '';
        }
      });
    },

    submitForm() {
      this.$refs.regionForm.validate(valid => {
        if (valid) {
          this.$modal.loading("正在提交数据，请稍候...");
          if (this.regionForm.id) {
            updateRegion(this.regionForm).then(response => {
              this.$modal.closeLoading();
              this.$modal.msgSuccess(response.msg);
              this.dialogVisible = false;
              this.refreshTree();
            }).catch(() => {
              this.$modal.closeLoading();
            });
          } else {
            addRegion(this.regionForm).then(response => {
              this.$modal.closeLoading();
              this.$modal.msgSuccess(response.msg);
              this.dialogVisible = false;
              this.refreshTree();
            }).catch(() => {
              this.$modal.closeLoading();
            });
          }
        }
      });
    },

    handleDelete(data) {
      this.deleteRegionId = data.id;
      this.deleteRegionName = data.name;
      this.deleteRegionLevel = data.level;
      this.deleteDialogVisible = true;
    },

    confirmDelete() {
      this.$modal.loading("正在删除数据，请稍候...");
      deleteRegion(this.deleteRegionId).then(response => {
        this.$modal.closeLoading();
        this.$modal.msgSuccess(response.msg);
        this.deleteDialogVisible = false;
        this.refreshTree();
      }).catch(() => {
        this.$modal.closeLoading();
      });
    },

    getLevelText(level) {
      const levelMap = {
        1: '省份',
        2: '城市',
        3: '区县',
        4: '乡镇/街道'
      };
      return levelMap[level] || '';
    }
  },

  mounted() {
    // 为树组件添加引用
    this.$refs.regionTree = this.$el.querySelector('.region-tree');
    // 初始化激活的筛选参数
    this.activeFilterParams = { ...this.queryParams };
  }
};
</script>

<style scoped>
.region-management-container {
  padding: 15px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 50px);
}

.main-card {
  border-radius: 6px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  border: none;
}

.card-header {
  display: flex;
  align-items: center;
  padding: 15px 20px;
  border-bottom: 1px solid #f2f2f2;
}

.title {
  font-size: 16px;
  font-weight: 600;
  color: #1f2d3d;
}

.search-container {
  padding: 15px 20px;
  background-color: #fafafa;
  border-bottom: 1px solid #f2f2f2;
}

.button-group {
  padding: 12px 20px;
}

.tree-container {
  padding: 15px 20px;
}

.region-tree {
  background-color: #fff;
  border: 1px solid #eaeef3;
  border-radius: 4px;
  min-height: 400px;
}

.tree-node-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  height: 38px;
  line-height: 38px;
  padding: 0 10px; /* 增加内边距，避免内容拥挤 */
  border-radius: 4px;
  transition: background-color 0.2s;
}

.tree-node-content:hover {
  background-color: #f5f7fa;
}

.node-info {
  flex: 0 0 250px; /* 固定宽度，根据需求调整 */
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  margin-right: 15px;
}
.node-location {
  flex: 0 0 280px; /* 固定宽度，确保布局稳定 */
  display: flex;
  gap: 15px; /* 经度和纬度之间的间距 */
  color: #86909c; /* 灰色文字，次要信息 */
  font-size: 12px;
}

.node-code {
  color: #86909c;
  font-size: 12px;
  margin-left: 8px;
}

.node-meta {
  display: flex;
  align-items: center;
  gap: 12px;
  color: #4e5969;
  flex: 1;
  justify-content: flex-end; /* 右对齐，确保操作按钮在最右侧 */
}

.node-level {
  font-size: 12px;
  color: #86909c;
  background-color: #f2f3f5;
  padding: 0 6px;
  border-radius: 12px;
}

.node-status {
  font-size: 12px;
  padding: 0 6px;
  border-radius: 12px;
}

.status-normal {
  background-color: #f0fff4;
  color: #00b42a;
}

.status-disabled {
  background-color: #fff2f3;
  color: #f53f3f;
}

.node-actions {
  display: flex;
  align-items: center;
  gap: 5px;
}

.action-btn {
  color: #4e5969;
  padding: 0 6px;
  font-size: 14px;
}

.action-btn:hover {
  color: #1890ff;
}

.delete-btn:hover {
  color: #f53f3f !important;
}
</style>
